#include "../include/UserLoginSection.h"
#include "../include/MySQLClient.hpp"
#include "../include/MyLogger.hpp"
#include "../include/userMananger.hpp"

#include <iostream>
#include <stdlib.h>
#include <crypt.h>
using std::cout;
using std::endl;



namespace rocket
{


void UserLoginSection1::process() 
{
    //客户端向服务端发送登录用户名
    
    //服务端接收登录用户名
    string user_login=_packet._msg;
    //服务端通过用户名查询用户的数据
    vector<vector<string>>result=rlt::MySQLClient::getInstance()->read_operation(string("SELECT user_salt, user_encrypted FROM account WHERE user_name ='")+user_login+"';");
    
    //判断用户是否注册过
    if(result.size()==0)
    {
        _conn->sendInLoop(wd::TLV(TASK_TYPE_LOGIN_SECTION1_RESP_ERROR,0,"") );
    }
    else
    {
        for(auto elem1:result)
        {
            for (auto elem2:elem1)
            {
                cout<<elem2<<"  ";
            }
            cout<<endl;
        }


        //从用户的数据中获取到用户的盐值和密文
        string salt=result.at(1).at(0);
        cout<<"salt="<<salt<<endl;

        string encrypted=result.at(1).at(1);
        cout<<"encrypted="<<encrypted<<endl;

        user client(user_login,salt,_conn,USER_IS_LOGINING,encrypted);
        //将用户信息保存到userMananger中
        userMananger::get_instance()->add_user(_conn->getfd(), client);
        //将盐值发送给客户端
        _conn->sendInLoop(wd::TLV(TASK_TYPE_LOGIN_SECTION1_RESP_OK,salt.size(),salt.c_str()) );

        
    }    
}

void UserLoginSection2::process() 
{

    //服务端接收来自客户端的密文

    //根据链接的文件描述符从userMananger中获取到用户信息
    user *client= userMananger::get_instance()->get_user(_conn->getfd());
    
    //从用户的数据中获取到用户的密文
    string encrypted=client->_encrypted;

    cout<<"encrypted="<<encrypted<<endl;

    //将客户端发来的密文和存储的数据库中的密文进行比较
    if(_packet._msg==encrypted)
    {
        cout<<"OK"<<endl;
        _conn->sendInLoop(wd::TLV(TASK_TYPE_LOGIN_SECTION2_RESP_OK,0,""));
        //修改用户状态为已登录
        client->_status=USER_HAS_LOGIN;
    }
    else
    {
        cout<<"login failed"<<endl;
        _conn->sendInLoop(wd::TLV(TASK_TYPE_LOGIN_SECTION2_RESP_ERROR,0,""));

    }
    //服务端返回登录结果    
}

}//end of namespace wd

